<?php

/*
 * Usage:
 * 
 * Call:		hazard_view_by_latlng.php?lat=<lat>&lng=<lng>
 * Returns: 	JSON data structure for hazard information
 * 				
 */


ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On');

require_once 'JSON.php';

$query = <<<QUERY
SELECT
        (g.gridcode/10.0) as pga,
        AsKML(g.the_geom) as kml
FROM
        groundmotion as g
WHERE
        g.gridcode > 5
ORDER BY
        pga
DESC
QUERY;

$hazards = array();

// connect to db
$conn = pg_connect("dbname=rvha user=pgadmin password=pgadmin");
	if (!$conn)
	{
       	 	print "Unable to Connect to DB";
	        exit;
	}


$result = pg_query($query);

print <<<KML_TOP
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.2">
<Document>
	<name>Salt Lake County - Earthquake Shaking Intensity</name>
	<Style id="trb292">
		<LineStyle>
			<color>80337777</color>
			<width>0</width>
		</LineStyle>
		<PolyStyle>
			<color>b507b1e5</color>
			<outline>0</outline>
		</PolyStyle>
	</Style>
	<Style id="trb511">
		<LineStyle>
			<color>80448e8e</color>
			<width>0</width>
		</LineStyle>
		<PolyStyle>
			<color>7c00ffff</color>
			<outline>0</outline>
		</PolyStyle>
	</Style>
	<Style id="trb168">
		<LineStyle>
			<color>80226060</color>
			<width>0</width>
		</LineStyle>
		<PolyStyle>
			<color>b50d62cb</color>
			<outline>0</outline>
		</PolyStyle>
	</Style>
	<Style id="trb730">
		<LineStyle>
			<color>80114a4a</color>
			<width>0</width>
		</LineStyle>
		<PolyStyle>
			<color>b51414b1</color>
			<outline>0</outline>
		</PolyStyle>
	</Style>
	<Folder>
		<name>Salt Lake County - Earthquake Shaking Intensity</name>
		<open>1</open>
		<description>(add citation/credits here)</description>
		<Folder>
			<name>Violent shaking</name>
KML_TOP;

$counter = 0;
while( $arr = pg_fetch_array($result))
{
	$pga = round($arr["pga"], 2);
	$kml = $arr["kml"];
	print "\n<Placemark id=\"$counter\">";
	print "<styleUrl>#trb730</styleUrl>";
	print "$kml";
	print "</Placemark>";
	$counter++;
}

print <<<KML_BOTTOM

		</Folder>
	</Folder>
</Document>
</kml>

KML_BOTTOM;


exit;

function calculateMMI($pga)
{
	/*
	 * 0.1-0.25 = MMI:VI
	 * 0.25-0.35 = MMI:VII
	 * 0.35-0.65 = MMI:VIII
	 * 0.65-+ = MMI:IX 
	 */
	$mmi = "";
	
	// VI
	if( ($pga >= 0.1) && ($pga < 0.2) )
	{
		$mmi = "VI";
	}
	
	// VI or VII
	if( ($pga == 0.2) || ($pga == 0.3) )
	{
		$mmi = "VI|VII";
	}
	
	// VIII
	if( ($pga > 0.3) || ($pga <= 0.5) )
	{
		$mmi = "VIII";
	}
		
	// VIII or IX
	if( ($pga == 0.6) || ($pga == 0.7) )
	{
		$mmi = "VIII|IX";
	}
		
	if( ($pga > 0.7) )
	{
		$mmi = "IX";
	}

	return $mmi;
}
?>